package com.hue.gulimail.gulimailorder.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;


/**
 * @Author: 姚凤桥
 * @Date: 2021/12/30 22:06
 * @Description: 使用MQ来模拟延时队列(加入到容器中的组件默认会创建在mq中 ， 前提是这个组件在mq中不存在)
 */
@Configuration
public class DelayQueueConfig {
    /**
     * 创建死信队列
     *
     * @return
     */
    @Bean
    public Queue orderDelayQueue() {
        Map<String, Object> arguments = new HashMap<>();
        //消息过期后将消息发送给名为order-event-exchange的路由
        arguments.put("x-dead-letter-exchange", "order-event-exchange");
        //消息过期后发送给其他交换机时的路由key为order.release.order
        arguments.put("x-dead-letter-routing-key", "order.release.queue");
        //队列的消息过期时间为60s
        arguments.put("x-message-ttl", 120000);

        Queue queue = new Queue("order.delay.queue", true, false, false, arguments);
        return queue;
    }

    /**
     * 创建一个普通队列，用来接受死信队列过期的消息
     *
     * @return
     */
    @Bean
    public Queue orderReleaseQueue() {
        return new Queue("order.release.queue", true, false, false);
    }

    /**
     * 创建一个普通的交换机
     *
     * @return
     */
    @Bean
    public Exchange orderEventExchange() {
        return new TopicExchange("order-event-exchange", true, false);
    }

    /**
     * 创建死信队列和交换机的绑定关系
     *
     * @return
     */
    @Bean
    public Binding orderDelayQueueBinding() {
        return new Binding("order.delay.queue",
                Binding.DestinationType.QUEUE,
                "order-event-exchange",
                "order.create.queue",
                null);
    }

    /**
     * 创建普通队列和交换机的绑定关系
     *
     * @return
     */
    @Bean
    public Binding orderReleaseQueueBinding() {
        return new Binding("order.release.queue",
                Binding.DestinationType.QUEUE,
                "order-event-exchange",
                "order.release.queue",
                null);
    }

    /**
     * 创建一个队列来接受秒杀成功的消息
     *
     * @return
     */
    @Bean
    public Queue queue() {
        return new Queue("order.seckill.queue", true, false, false);
    }

    @Bean
    public Binding binding() {
        return new Binding("order.seckill.queue"
                , Binding.DestinationType.QUEUE,
                "order-event-exchange",
                "order.seckill.queue",
                null);
    }
}
